package com.msk.common.wechatV3.service;

import com.msk.common.utils.StringUtils;
import com.msk.common.wechatV3.base.CommonOrder;
import com.msk.common.wechatV3.config.WxPayV3Config;
import com.msk.common.wechatV3.pojo.combined.PayUrlConstant;
import com.msk.common.wechatV3.pojo.combined.bo.placeorder.Amount;
import com.msk.common.wechatV3.pojo.combined.bo.placeorder.CombinePayerInfo;
import com.msk.common.wechatV3.pojo.combined.bo.placeorder.CombinedPayBo;
import com.msk.common.wechatV3.pojo.combined.bo.placeorder.SubOrders;
import com.msk.common.wechatV3.pojo.only.vo.initiatepayment.WxPayResult;
import com.msk.common.wechatV3.util.MakeOrderNum;
import com.msk.common.wechatV3.util.WxComBinedPayV3Util;
import com.msk.common.wechatV3.util.WxPayV3Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @desc: 微信合单支付支付V3服务
 * @author: dz
 * @date: 2022-05-09 11:59
 **/
@Service
public class WeixinPayCombinedV3Service {

    @Autowired
    private WxPayV3Config wxPayV3ConfigDefault;

    /**
     * @description: 微信小程序合单支付
     * @author: dz
     * @date: 2022/10/8 14:45
     * @param: [commonOrders, openid,mainOrderNo] 子订单集合，openid,合单商户订单号
     * @return: java.util.Map<java.lang.String,java.lang.Object>
     **/
    public Map<String, Object> weixinJsapiCombinedPayV3(List<CommonOrder> commonOrders, String openid,String mainOrderNo) throws Exception {
        Map<String, Object> result = new HashMap<String, Object>();

        String combine_out_trade_no = "";
        if(StringUtils.isEmpty(mainOrderNo)){
            combine_out_trade_no = MakeOrderNum.getOrderNo();
        }else{
            combine_out_trade_no = mainOrderNo;
        }
        String combine_appid = "";
        String combine_mchid = "";
        List<SubOrders> sub_orders = new ArrayList<>();
        String notify_url="";
        String serial_no = "";
        String privateKeyFilePath = "";
        if(!CollectionUtils.isEmpty(commonOrders)){
            for (CommonOrder commonOrder:commonOrders) {
                SubOrders subOrders = new SubOrders();
                WxPayV3Config wxPayV3Config = this.getWxPayV3Config(commonOrder.getWxPayV3Config());
                combine_appid = wxPayV3Config.getAppId();// 微信开放平台审核通过的应用APPID
                String mchid = wxPayV3Config.getMchId();
                combine_mchid = wxPayV3Config.getMchId();
                String out_trade_no = commonOrder.getOrderNo();
                String description = "订单编号：" + out_trade_no;
                BigDecimal orderAmount = commonOrder.getOrderAmount();
                int total_fee = (int) (Math.round(orderAmount.doubleValue() * 100));
                notify_url = commonOrder.getNotifyUrl();//通知地址
                String attach = commonOrder.getAttach();//附加数据
                serial_no = wxPayV3Config.getSerialNumber();//证书序列号
                privateKeyFilePath = wxPayV3Config.getWxPayPrivateKey();//私钥路径
                //订单金额信息
                Amount amount = new Amount();
                amount.setCurrency("CNY");
                amount.setTotal_amount(total_fee);

                subOrders.setMchid(mchid);
                subOrders.setAttach(attach);
                subOrders.setOut_trade_no(out_trade_no);
                subOrders.setDescription(description);
                subOrders.setAmount(amount);
                sub_orders.add(subOrders);
            }
        }
        CombinePayerInfo combinePayerInfo = new CombinePayerInfo();
        combinePayerInfo.setOpenid(openid);


        //下单请求参数
        CombinedPayBo combinedPayBo = new CombinedPayBo(combine_appid,combine_mchid,combine_out_trade_no,sub_orders,combinePayerInfo, notify_url);
        //V3需要先调用下单接口生成  预支付交易会话标识 prepay_id
        Map<String, String> stringStringMap = WxComBinedPayV3Util.v3ComBinedPayGet(PayUrlConstant.jsPlaceOrderUrl, combinedPayBo, combine_mchid, serial_no, privateKeyFilePath);
        String prepayid = stringStringMap.get("prepay_id");
        if(StringUtils.isNull(prepayid)){
            String code = stringStringMap.get("code");
            String message = stringStringMap.get("message");
            result.put("code", "0");
            result.put("message", "错误代码：["+code+"],错误信息："+message);
            return result;
        }
        //小程序V3的签名，使用字段appId、timeStamp、nonceStr、package计算得出的签名值
        //签名需要 使用商户私钥对待签名串进行SHA256 with RSA签名，并对签名结果进行Base64编码得到签名值。
        WxPayResult wxPayResult = WxPayV3Util.wxMpTuneUp(prepayid, combine_appid,combine_mchid,privateKeyFilePath);
        result.put("data", wxPayResult);
        result.put("code", "1");
        result.put("message", "发起支付成功");
        return result;
    }

    /**
     * 动态获取微信支付配置
     * @return
     */
    public WxPayV3Config getWxPayV3Config(WxPayV3Config wxPayV3Config) {
        if (wxPayV3Config == null) {
            wxPayV3Config = wxPayV3ConfigDefault;
        }
        return wxPayV3Config;
    }

}
